package com.aizuda.lucky;

import feign.Feign;
import feign.httpclient.ApacheHttpClient;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Lucky {

    public static <T> T feignTarget(Class<T> apiType, String url) {
        return Feign.builder().client(new ApacheHttpClient())
                .encoder(new JacksonEncoder())
                .decoder(new JacksonDecoder()).target(apiType, url);
    }

    public static List<String> getAllStars(String accessToken, BiFunction<String, Integer, List<Map<String, Object>>> biFunction,
                                           Function<Map<String, Object>, String> function) {
        List<String> users = new ArrayList<>();
        int i = 1;
        while (true) {
            List<Map<String, Object>> stars = biFunction.apply(accessToken, i);
            if (null == stars || stars.isEmpty()) {
                break;
            }
            users.addAll(stars.stream().map(function).collect(Collectors.toList()));
            i++;
        }
        return users;
    }

    public static void main(String[] args) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 填充数据
        List<String> users = new ArrayList<>();
        users.addAll(getAllStars(GitHubClient.accessToken, feignTarget(GitHubClient.class, "https://api.github.com")::getStars,
                t -> "github_" + t.get("login")));
        users.addAll(getAllStars(GitEeClient.accessToken, feignTarget(GitEeClient.class, "https://gitee.com")::getStars,
                t -> t.get("name") + "_" + t.get("login")));

        // 创建数据行
        int i = 0;
        for (String user : users) {
            Row dataRow = sheet.createRow(i++);
            Cell cell = dataRow.createCell(0);
            cell.setCellValue(user);
        }

        // 写入文件
        try (FileOutputStream fileOut = new FileOutputStream("users.xlsx")) {
            workbook.write(fileOut);
        } finally {
            workbook.close();
        }
    }
















}
